I.はじめに
Canvas は h5 の新機能である html5 の新しいタグです. グラフィック コンテナでもあります. 簡単に言えば, 四角形, 円, ポリラインなどを描くことができるキャンバスです. JavaScript によって制御されます. is スクリプトはグラフを描画します。
2.効果を実感する
今日の小さなキャンバスケースは主に4つの機能を持っています
1. 線を引く 2. 長方形 3. 円 4. ブラシの太さを変更できます 5. 画板をクリアします
3. コードの実装
1.html+css 部分コード
<style>
canvas{
background-color: #ccc;
border: 1px solid;
}
div{
position:absolute;
/* left: 300px; */
left: 300px;
}
</style>
</head>
<body>
<!--
1. 画线
2. 矩形
3. 圆形
4. 可以改变画笔的粗细
-->
<canvas width="800" height="800"></canvas>
<div>
<button>线条</button>
<button>矩形</button>
<button>圆形</button>
<button>加粗</button>
<button>变细</button>
<button>清除</button>
</div>
2.js コード
<script>
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var btn = document.getElementsByTagName('button');
var chu = 1;
console.log(btn);
//线条
btn[0].onclick = function(){
// console.log(111);
canvas.onmousedown = function(e){
// console.log(chu);
ctx.beginPath();
if(chu<1){
chu=1;
}
ctx.lineWidth = chu;
//获取线的起点
ctx.moveTo(e.offsetX,e.offsetY)
canvas.onmousemove =function(e){
//获取线的终点
ctx.lineTo(e.offsetX,e.offsetY);
//填充颜色
ctx.stroke();
// ctx.closePath();
}
}
}
//矩形
btn[1].onclick = function(){
canvas.onmousedown = function(e){
// ctx.beginPath();
var startX = e.offsetX;
var startY =e.offsetY;
canvas.onmouseup =function(e){
ctx.beginPath();
ctx.lineWidth = chu;
if(chu<1){
chu=1;
}
ctx.rect(startX,startY,e.offsetX-startX,e.offsetY-startY)
ctx.stroke();
ctx.closePath();
}
}
}
// 圆形
btn[2].onclick = function(){
canvas.onmousedown = function(e){
ctx.beginPath();
var startX = e.offsetX;
var startY =e.offsetY;
canvas.onmouseup =function(e){
// ctx.beginPath();
ctx.lineWidth = chu;
if(chu<1){
chu=1;
}
ctx.arc(startX,startY,e.offsetX-startX,0,Math.PI*2)
ctx.stroke();
ctx.closePath();
}
// pan.closePath();
}
}
//取消canva鼠标移动事件鼠标松开取消移动监听
document.body.onmouseup = function(){
canvas.onmousemove =null;
canvas.onmouseup=null;
}
//清除
btn[5].onclick = function(){
ctx.clearRect(0, 0, 800, 800);
}
//粗
btn[3].onclick = function(){
chu+=2;
}
//细
btn[4].onclick = function(){
chu-=2;
}
</script>
4.まとめ
Canvas は非常に強力な機能であり、これは氷山の一角にすぎません。ぜひ参考にしてください。これは将来の使用の便宜のために記録されたものであり、大物がより多くのコミュニケーションを取り、多くのメッセージを残し、私の欠点を指摘できることを願っています! 困っている友達が研究できる!!