javascript - 如何使用 HTML5 <canvas> clip()

标签 javascript html canvas clip

我是 HTML5 新手 <canvas>并试图做点什么,实际上画了 PORTAL2 标志 :)。

到目前为止我已经明白了

enter image description here

但是你可以看到腿从墙上突出来了,我想知道如何去除多余的油漆。

我想这可以用 clip() 来完成功能,但我不确定如何使用它。

这是我想要的

enter image description here

这是我正在尝试的代码,也可以在 JS Bin 此处获得 http://jsbin.com/exado5/edit

//function to convert deg to radian
function acDegToRad(deg)
{
     return deg* (-(Math.PI / 180.0));    
}

//set fill color to gray
ctx.fillStyle = "rgb(120,120,120)";
//save the current state with fillcolor
ctx.save();

//draw 2's base rectangle
ctx.fillRect(20,200,120,35);
//bring origin to 2's base
ctx.translate(20,200);
//rotate the canvas 35 deg anti-clockwise
ctx.rotate(acDegToRad(35));
//draw 2's slant rectangle
ctx.fillRect(0,0,100,35);
//restore the canvas to reset transforms
ctx.restore();
//set stroke color width and draw the 2's top semi circle
ctx.strokeStyle = "rgb(120,120,120)";
ctx.lineWidth = 35;
ctx.beginPath();
ctx.arc(77,135,40,acDegToRad(-40),acDegToRad(180),true);
ctx.stroke();

//reset canvas transforms
ctx.restore();

//change color to blue
ctx.fillStyle = "rgb(0,160,212)";
//save current state of canvas
ctx.save();
//draw long dividing rectangle 
ctx.fillRect(162,20,8,300);
//draw player head circle
ctx.beginPath();
ctx.arc(225,80,35,acDegToRad(0),acDegToRad(360));
ctx.fill();

//start new path for tummy :)
ctx.beginPath();
ctx.moveTo(170,90);
ctx.lineTo(230,140);
ctx.lineTo(170,210);
ctx.fill();

//start new path for hand
//set lineCap and lineJoin to "round", blue color 
//for stroke, and width of 25px
ctx.lineWidth = 25;
ctx.lineCap = "round";
ctx.strokeStyle = "rgb(0,160,212)";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(222,150);
ctx.lineTo(230,190);
ctx.lineTo(270,220);
ctx.stroke();

//begin new path for drawing leg
ctx.beginPath();
ctx.moveTo(160,210);
ctx.lineTo(195,260);
ctx.lineTo(160,290);
ctx.stroke();

请帮忙。

最佳答案

添加这个:

...
//reset canvas transforms
ctx.restore();

ctx.beginPath();
ctx.moveTo(162, 20);
ctx.lineTo(162, 320);
ctx.lineTo(300, 320);
ctx.lineTo(300, 20);
ctx.clip();

//change color to blue
ctx.fillStyle = "rgb(0,160,212)";
//save current state of canvas
...

关于javascript - 如何使用 HTML5 <canvas> clip(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5801116/

相关文章:

javascript - 如何在大型 SPA 中处理和记录 Javascript 错误

javascript - 将用户的十进制输入与c#十进制金额进行比较

javascript - 未捕获的类型错误 : Cannot read property 'createMediaElementSource' of null

javascript - 为什么 Canvas 停止清除矩形?

javascript - 比较文件中的图像和从 Canvas 创建的图像

javascript - IOS10 全屏 safari Javascript

javascript - 在 optgroup 中选择选项后转到 URL

html - 在页面上居中带有边框的div

html - 将不同的媒体样式表与打印样式表一起使用

javascript - http ://sigmajs. org/les 教程 - 为什么我的 Canvas 高度为 0?