详解HTML5 canvas绘图基本使用方法

2020-04-21 23:48:31易采站长站整理

<a href="#">xor</a>
</div>
</body>
<script type="text/javascript">

window.onload = function(){
draw("source-over");

var buttons = document.getElementById("buttons").getElementsByTagName("a");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function(){
draw(this.text);
return false;
};
}
};

function draw(compositeStyle){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.clearRect(0, 0, canvas.width, canvas.height);

//draw title
context.font = "bold 40px Arial";
context.textAlign = "center";
context.textBasedline = "middle";
context.fillStyle = "#150E0E";
context.fillText("globalCompositeOperation = "+compositeStyle, canvas.width/2, 60);

//draw a rect
context.fillStyle = "#F6082A";
context.fillRect(300, 150, 500, 500);

//draw a triangle
context.globalCompositeOperation = compositeStyle;
context.fillStyle = "#1611F5";
context.beginPath();
context.moveTo(700, 250);
context.lineTo(1000,750);
context.lineTo(400, 750);
context.closePath();
context.fill();
}

</script>
</html>

读者可以点击标签来观察不同的组合效果,效果如下:

剪辑区域:

clip()方法从原始画布中剪切任意形状和尺寸。

提示:一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)。您也可以在使用 clip() 方法前通过使用 save() 方法对当前画布区域进行保存,并在以后的任意时间对其进行恢复(通过 restore() 方法)

以下是用一个圆去截取一个矩形的示例:


var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.beginPath();
context.fillStyle = "#0C0101";
context.fillRect(0,0,canvas.width,canvas.height);

context.beginPath();
context.fillStyle = "#FFFDFD";
context.arc(400,400,100,0,2*Math.PI);
context.fill();
context.clip();

context.beginPath();
context.fillStyle = "#F60825";
context.fillRect(200, 350, 400,50);

除了上述的属性的和方法,还有以下等方法:

drawImage(): 向画布上绘制图像、画布或视频。

toDataURL() :保存图形

isPointInPath(): 如果指定的点位于当前路径中,则返回 true,否则返回 false。