Javascript 无法在画布上绘制矩形

Javascript 无法在画布上绘制矩形,javascript,html,canvas,Javascript,Html,Canvas,我正在用白色背景色在画布上画一幅图像。我想在图像上画一个边框,但我无法这样做。这是我的密码: var canvas = parent.document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext('2d'); context.fillStyle = "black"; context.font = "50px Ar

我正在用白色背景色在画布上画一幅图像。我想在图像上画一个边框,但我无法这样做。这是我的密码:

var canvas = parent.document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
//context.fillText(chartId, canvas.width-200, 50);
context.drawImage(image, 0, 0);
context.fillStyle = "#000000";
context.rect(0,0,canvas.width,canvas.height);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#FFFFFF";

但是我下载这张图片时没有看到任何边框。

你忘了画你的直肠

context.stroke();

看起来,您没有执行
context.stroke()
操作?

缺少两件事

  • context.stroke()绘制矩形后
  • 您应该使用
    context.beginPath()开始绘制
    rect()
    。这是为了避免下一个笔划也影响您绘制的第一个矩形
  • 另一种可能的解决方案是使用函数context.strokert();省去了使用path()和stroke()的麻烦

        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext('2d');
        context.fillStyle = "black";
        context.font = "50px Arial";
        //context.fillText(chartId, canvas.width-200, 50);
        context.drawImage(image, 0, 0);
        context.fillStyle = "#000000";
        context.beginPath();
        context.rect(0,0,canvas.width,canvas.height);
        context.stroke();
        context.globalCompositeOperation = "destination-over";
        context.fillStyle = "#FFFFFF";