我正在尝试将图像添加到画布对象中,但对于我的生活,我无法弄清楚如何使其正确显示。它显示画布对象(圆圈),但不显示图像。
这是我的画布HTML:
<canvas id="leaf" width="60" height="60" style="border:1px solid #d3d3d3;"></canvas>
以下是相关的JS:
let canvas = <HTMLCanvasElement>document.getElementById('leaf');
let context = canvas.getContext('2d');
let imageObj = new Image();
imageObj.onload = function()
{
context.save();
context.beginPath();
context.arc(30, 30, 28, 0, 2 * Math.PI);
context.clip();
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
context.restore();
context.beginPath();
context.arc(30, 30, 28, 0, 2 * Math.PI);
context.drawImage(imageObj, 0, 0);
context.strokeStyle = 'red';
context.stroke();
console.log(canvas.toDataURL());
return canvas.toDataURL();
答案 0 :(得分:0)
我发现这是由于return canvas.toDataURL();
被抢先调用,所以我把它移到了image.load()函数中,现在它显示正确!