画布<canvas> 标签定义图形,比如图表和其他图像,您必须使用脚本来绘制图形。
首先我们再html里面定义一个画布
<canvas id="huabu" height="720" width="750" style="border:1px solid #d3d3d3;"></canvas>
然后画布的基础js
var c=document.getElementById("huabu"); var ctx=c.getContext("2d");
getContext() 方法返回一个用于在画布上绘图的环境。但是jq的对象是没有绘图的!所以我们如果使用jq就要把他转化为dom
var c = $("#huabu").get(0); var ctx = c.getContext("2d");//返回绘画的构图环境
然后我们来画个矩形吧!
ctx.fillStyle="#FF0000";//设置颜色,默认为000 ctx.fillRect(0,0,150,75);// 矩形 x轴,y轴,w宽,h高 以画布左上角为起点
效果图:
坐标参考
<html> <head> <title>长沙</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" /> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1> <meta name=" viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0;"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content=""> <meta name="format-detection" content="telphone=no, email=no"> <meta name="renderer" content="webkit"> <meta name="HandheldFriendly" content="true"> <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <body> <div id="coordiv" onmousemove="cnvs_getCoordinates(event)" onmouseout="cnvs_clearCoordinates()"> <canvas id="huabu" height="720" width="750" style="border:1px solid #d3d3d3;"> </canvas> </div> <div id="xycoordinates"></div> <script type="text/javascript"> //var c=document.getElementById("huabu"); //var ctx=c.getContext("2d"); var c = $("#huabu").get(0); var ctx = c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75); ctx.moveTo(236,422); ctx.lineTo(422,422); ctx.lineTo(287,554); ctx.lineTo(328,355); ctx.lineTo(387,554); ctx.lineTo(236,422); ctx.stroke(); ctx.beginPath(); ctx.arc(195,250,40,0,2*Math.PI); ctx.stroke(); ctx.font="30px Arial"; ctx.fillText("Hello World",420,50); // 创建渐变 var grd=ctx.createRadialGradient(95,50,15,90,60,100); grd.addColorStop(0,"red"); grd.addColorStop(1,"white"); // 填充渐变 ctx.fillStyle=grd; ctx.fillRect(90,90,150,380); </script> <script> function cnvs_getCoordinates(e) { x=e.clientX; y=e.clientY; document.getElementById("xycoordinates").innerHTML="坐标X,Y: (" + x + "," + y + ")"; } </script> </body> </html>