<title>无标题文档</title>
</head>
<body>
<canvas id="trails" style="border:2px solid;" width="200" height="200">
<script>
function createCanopyPath(context)//取得canvas元素及其绘图上下文
{
context.beginPath();
context.moveTo(-25,-50);
context.lineTo(-10,-80);
context.lineTo(-20,-80);
context.lineTo(-5,-110);
context.lineTo(-15,-110);
context.lineTo(0,-140);
context.lineTo(15,-110);
context.lineTo(5,-110);
context.lineTo(20,-80);
context.lineTo(10,-80);
context.lineTo(25,-50);
context.closePath();
}
function drawTrails()
{
var canvas=document.getElementById('trails');
var context=canvas.getContext('2d');
context.save();
context.translate(130,-250);
context.lineWidth=4;
context.lineJoin='round';
createCanopyPath(context);
context.stroke();
context.restore();
}
</script>
</canvas>
</body>
</html>
------解决方案--------------------
<body onload='drawTrails()' >
------解决方案--------------------
createCanopyPath(context)这个方法里面的moveTo已经将画笔移到画布的外面去了。整个canvas的左上角是坐标(0,0)。所以,如此一来,就算你会出来了,你也看不到的。。试试调个位置吧!
------解决方案--------------------
额。。。。我没看你代码,但有个问题是很明显的,你写了两个函数,你没告诉网页加载后执行那个。。所以你只能看到canvas
你加上这句话,在script里,那两个函数后面:
window.addEventListener("load",drawTrails,true);
这下面是我写的完整的画树的代码:
这个和上面你的有不同,你看我把window那句话屏蔽掉了,但我在开头定义图像时onload了,所以做法不同,但起得效果是一样的
<html>
<head>
<title>Html5_Canvas_Paint</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="600" style="border:1px solid #FF0000;"></canvas>
<script>
var gravel=new Image();
gravel.src="gravel.jpg";
gravel.onload=function(){
drawTrails();
}
function createCanopyPath(context){
context.beginPath();
context.moveTo(-25,-50);
context.lineTo(-10,-80);
context.lineTo(-20,-80);
context.lineTo(-5,-110);
context.lineTo(-15,-110);
context.lineTo(0,-140);
context.lineTo(15,-110);
context.lineTo(5,-110);
context.lineTo(20,-80);
context.lineTo(10,-80);
context.lineTo(25,-50);
context.closePath();
}
function createTree(context){
context.save();
context.transform(1,0,-0.5,1,0,0);
context.scale(1,0.6);
context.fillStyle='rgba(0,0,0,0.2)';
context.fillRect(-10,-50,20,50);
createCanopyPath(context);
context.fill();
context.restore();
//创建用于树干纹理的三阶渐变
var trunkGradient=context.createLinearGradient(-10,-50,20,-50);
//树干的左侧边缘是一般程度的棕色
trunkGradient.addColorStop(0,"#663300");
//树干中间偏左的位置颜色要淡一些
trunkGradient.addColorStop(0.4,"#996600");
//树干右侧边缘的颜色要深一些
trunkGradient.addColorStop(1,"#552200");
/*trunkGradient.addColorStop(0,"#FF0000");
trunkGradient.addColorStop(1,"#00FF00");*/
//使用渐变色填充树干
context.fillStyle=trunkGradient;
context.fillRect(-10,-50,20,50);
//创建垂直渐变,以用作树冠在树干上的投影
var trunkShadow=context.createLinearGradient(0,-50,0,0);
//投影的起点是透明度为50%的很色
trunkShadow.addColorStop(0,'rgba(0,0,0,0.5)');
//方向垂直向下,在很短的时间内颜色迅速渐变至透明色,这段长度之外的树干上没有投影
trunkShadow.addColorStop(0.2,'rgba(0,0,0,0.0)');