我希望使用HTML5画布实现以下目标:
我的代码: jsfiddle
为什么我画的矩形不会覆盖之前的图像? 有时候重新加载网站时,画布绘制的方式也很奇怪。
![goal](https://istack.dev59.com/40tSQ.webp)
// Options
var maxImageWidth = 250,
maxImageHeight = 196,
radius = 50;
var canvas = $('#ddayCanvas'),
canvasWidth = canvas.width(),
canvasHeight = canvas.height(),
sectorColor = $('.product-box').css('background-color'),
context = canvas[0].getContext('2d'),
imageSrc = canvas.data('image');
function drawDday (option) {
var imageObj = new Image();
imageObj.onload = function() {
if (option == 'clip'){
context.save();
context.clip();
}
var imageWidth = imageObj.width,
imageHeight = imageObj.height;
if (imageWidth > maxImageWidth){
imageHeight = imageHeight - (imageWidth - maxImageWidth);
imageWidth = maxImageWidth;
}
if (imageHeight > maxImageHeight) {
imageWidth = imageWidth - (imageHeight - maxImageHeight);
imageHeight = maxImageHeight;
}
context.drawImage(imageObj, Math.ceil((canvasWidth - imageWidth) / 2), Math.ceil((canvasHeight - imageHeight) / 2), imageWidth, imageHeight);
};
imageObj.src = imageSrc;
}
drawDday();
// Why does this rectangle not overlay the previous image?
context.fillStyle = sectorColor;
context.fillRect(0, 0, canvasWidth, canvasHeight);
drawDday('clip');
context.restore();
context.moveTo(0, 0);
context.beginPath();
context.fillStyle = '#fff';
context.arc(canvasWidth / 2, canvasHeight/2, radius, 0, 2*Math.PI);
context.fill();
为什么我画的矩形不会覆盖之前的图像? 有时候重新加载网站时,画布绘制的方式也很奇怪。