javascript 如何在画布周围绘制边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31045689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw border around canvas
提问by ValarDohaeris
I am drawing an image on a canvas with white background color. I want to draw a border around the canvas and I am unable to do so. Here is my code:
我正在用白色背景色在画布上绘制图像。我想在画布周围画一个边框,但我无法这样做。这是我的代码:
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
context.fillText(chartId, 0, 50);
context.drawImage(image, 0, 0);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#FFFFFF";
context.fillRect(0,0,canvas.width,canvas.height);//for white background
after this i want a red border to appear around the whole canvas.
在此之后,我希望在整个画布周围出现一个红色边框。
回答by fuyushimoya
Set context.lineWidth
to 2
, set context.strokeStyle
to #FF0000"
, and use context.strokeRect
, not fillRect
.
globalCompositeOperation
if set to destination-over
, then the newly apply thing will use canvas's value, so change to source-over
. Used lightblue
to fake the drawImage
in your code
设置context.lineWidth
为2
,设置context.strokeStyle
为#FF0000"
,并使用context.strokeRect
,而不是fillRect
。
globalCompositeOperation
如果设置为destination-over
,则新应用的东西将使用画布的值,因此更改为source-over
。用于lightblue
伪造drawImage
代码中的
var canvas = document.getElementById('cv');
canvas.width = 400;
canvas.height = 300;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
context.fillText('ASD', 0, 50);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#00FFFF";
context.fillRect(0,0,canvas.width,canvas.height);//for white background
context.globalCompositeOperation = "source-over";
context.lineWidth = 2;
context.strokeStyle="#FF0000";
context.strokeRect(0, 0, canvas.width, canvas.height);//for white background
<canvas id="cv"></canvas>