<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>canvas</title> <script type="text/javascript" src="../js/jQuery.js"></script> <style type="text/css"> *{ margin: 0; padding: 0; outline: none; border: none; } #canvas{ margin: auto auto; width: 7rem; margin: .25rem 0 0 1.5rem; border: 1px solid black; } </style> </head> <body> <canvas id="canvas" width="1000" height="600"></canvas> </body> </html> <script type="text/javascript"> /** * rem 布局初始化 */ $('html').css('font-size', $(window).width()/10); /** * 获取 canvas 画布 * 获取 canvas 绘图上下文环境 */ var canvas = $('#canvas')[0]; var cxt = canvas.getContext('2d'); /** * canvas 绘制矩形的方法 一 * rect(矩形的左上定点横坐标, 矩形的左上定点纵坐标, 矩形的宽度, 矩形的高度) * 该方法只是描述了 矩形的路径, 需要调用画线或者填充的方法才能起作用 */ cxt.fillStyle = 'yellow'; cxt.rect(200, 100, 400, 300); //cxt.stroke(); cxt.fill(); /** * 绘制矩形的方法二 * fillRect(矩形的左上定点横坐标, 矩形的左上定点纵坐标, 矩形的宽度, 矩形的高度) * strokeRect(矩形的左上定点横坐标, 矩形的左上定点纵坐标, 矩形的宽度, 矩形的高度) * 这两个方法会直接绘制出图形 */ cxt.fillStyle = 'red'; //cxt.strokeRect(400, 200, 400, 300); cxt.fillRect(400, 200, 400, 300); </script>