<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML5 canvas 设置背景图</title> <script src="canvas2image.js"></script> </head> <body> <canvas id="canvaxbox" width="500" height="500"></canvas> </body> <script> var c = document.getElementById("canvaxbox"); var canvas = c.getContext("2d"); var img = new Image(); img.src = "pg1.JPG"; img.onload = imgfn;//图片加载完在执行 function imgfn() { var bg = canvas.createPattern(img, "no-repeat");//createPattern() 方法在指定的方向内重复指定的元素。 canvas.fillStyle = bg;//fillStyle 属性设置或返回用于填充绘画的颜色、渐变或模式。 canvas.fillRect(0, 0, c.width, c.height);//绘制已填充矩形fillRect(左上角x坐标, 左上角y坐标, 宽, 高) } </script> </html>