我想使用相同的图像在 Canvas 上多次绘制,换句话说,我想应用代码,当我单击 Canvas 区域时会生成一个图像,当我再次单击其他地方时它会生成另一个图像,所以上。
<canvas></canvas>
但是当尝试再次绘制时,它会替换先前绘制的图像,然后绘制新图像。而不是在 Canvas 上保留先前绘制的图像。
function drawAll(){
context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height,0, 0, 700, 618);
if(coordinates.length > 0){
coordinates.map((coord, key) =>{
context.beginPath();
context.moveTo(coord.startX, coord.startY);
context.lineTo(coord.toX,coord.toY);
context.strokeStyle="rgb(226, 104, 36)";
context.lineWidth=2;
context.stroke();
});
}
if(entry){
context.drawImage(imageObjBall, entry.posX-8, entry.posY-8, 16, 16);
}
}
EDIT: Hey sorry forgot to insert this bit down here
function handleClick(e){
if(!isDrawing && prize_id != null){
var pos = getMousePos(canvas, e);
mouseX = pos.x;
mouseY = pos.y;
$x_id=`#cor_x_${prize_id}`;
$y_id=`#cor_y_${prize_id}`;
context.clearRect(0, 0, 700, 618);
context.drawImage(imageObjBall, mouseX-8, mouseY-8, 16, 16);
entry={posX:mouseX,posY:mouseY};
$($x_id).text(mouseX);
$($y_id).text(mouseY);
drawAll();
}
}
NOTE: This is in laravel 5, there is more code outside of this but i felt this was the necessary snipped needed for you to be able to help me but if you need more please ask me to edit some more code into this post
最佳答案
要使用单个图像对象将多个图像绘制到 Canvas 上,请通过new Image()
创建图像对象。并设置src
相应的属性(property)。
或者,您也可以写 <img src="">
HTML 代码中的标记并通过 document.querySelector
获取对其的引用.
有一件重要的事情需要考虑:在调用 drawImage
之前,您必须确保图像已加载,即使没有加载时间(例如 localhost 或 data-url)。
在我的示例中,我通过不立即启动动画来解决这个问题。相反,requestAnimationFrame 循环是在图像 onload 事件中启动的。
var R = Math.random
var a = document.getElementById("a")
var W = a.width = 400
var H = a.height = 300
var c = a.getContext("2d")
var img = new Image()
img.src = 'https://assets-cdn.github.com/images/icons/emoji/unicode/1f60d.png'
function loop() {
var rndX = (R()*W)|0
var rndY = (R()*H)|0
c.drawImage(img, rndX, rndY)
requestAnimationFrame(loop)
}
img.onload=function() {
loop()
}
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
<canvas id="a"></canvas>
关于javascript - 如何将同一对象的多个图像绘制到单个 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43848141/