如何在 JavaScript 中在画布上绘制图像
以下是使用 JavaScript 在画布上绘制图像的代码 −
示例
<DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Drawing an image in canvas</h1> <img class="flower" width="300" height="300" src="https://i.picsum.photos/id/976/300/300.jpg?hmac=Gwae8T0kvhjbWyNIAiYgOckWbK BHGr2p_6EEE29uDDg" /> <canvas class="canvas1" width="300" height="300" style="border: 1px solid #d3d3d3;"> </canvas><br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to draw the image in canvas</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); BtnEle.addEventListener("click", () => { var c = document.querySelector(".canvas1"); var ctx = c.getContext("2d"); var img = document.querySelector(".flower"); ctx.drawImage(img, 10, 10); }); </script> </body> </html>
输出
单击“点击此处”按钮 −
广告