css
*{ margin: 0; padding: 0; margin-top: 10vh; } body{ text-align: center; } canvas{ margin: 0 auto; border: 1px solid #CCCCCC; }
js
<script type="text/javascript"> window.addEventListener('load',function(){ var canvas = document.createElement('canvas') document.body.appendChild(canvas) canvas.id = 'myCanvas' canvas.width = 600; canvas.height= 600; var myCanvas = document.getElementById('myCanvas') //检测浏览器是否支持canvas属性 if(!myCanvas||!myCanvas.getContext){ return } var ctx = myCanvas.getContext('2d') $$drawRect() useReact() useStokeRect() function $$drawRect(){ // ctx.setLineDash([25,5,5,5])//线段间隔长度 ctx.lineWidth = 2 ctx.fillStyle = '#F08080' ctx.strokeStyle = '#34C2E3' // ctx.lineCap = 'butt'//线段终起点 'butt' 'round' 'square' ctx.lineJoin = 'round'//线段的转折点 'round' 'bevel' 'miter' ctx.beginPath() ctx.moveTo(30,30) ctx.lineTo(150,30) ctx.lineTo(150,150) ctx.lineTo(30,150) ctx.closePath() // ctx.stroke()//绘制边框图像 ctx.fill()//填充 ctx.beginPath() ctx.moveTo(160,30) ctx.lineTo(280,30) ctx.lineTo(280,150) ctx.lineTo(160,150) ctx.closePath() ctx.stroke()//绘制边框图像 } function useReact(){ ctx.strokeStyle = '#FF3366' ctx.lineWidth = 2 ctx.fillStyle = '#008000' ctx.beginPath() ctx.rect(30,160,120,120) ctx.stroke() ctx.beginPath() ctx.rect(160,160,120,120) ctx.fill() } function useStokeRect(){ ctx.fillStyle = '#008000' ctx.fillRect(30,290,120,120) ctx.lineWidth = 2 ctx.strokeStyle = '#33EE66' ctx.strokeRect(160,290,120,120) } },false) </script>