Professional Documents
Culture Documents
Java Canvas
Java Canvas
Об'єкт canvas
Для малювання в javascript перш за все необхідно додати об'єкт canvas,
який імітує «полотно» художника.
Малювання прямокутника:
Залитий кольором прямокутник:
fillRect (x, y, width, height)
Прямокутний контур:
strokeRect (x, y, width, height)
Очищення прямокутної області (прозорий прямокутник):
clearRect (x, y, width, height)
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" > </canvas>
<script>
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width="300";
canvas.height="300"; Розміри за замовчуванням: 300 px × 150 px
ctx.fillStyle = 'rgb(200, 0, 0)'; (width × height), але можна
ctx.fillRect(10, 10, 50, 50); встановлювати довільні розміри.
ctx.fillStyle = 'rgba(0, 0, 100, 0.5)';
ctx.fillRect(30, 30, 50, 50);
</script>
</body>
</html>
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
Малювання шляхів в canvas
1. Створення шляху.
Коли шлях створений інші команди вже працюють над створеним шляхом:
ctx.beginPath ();
2. Вибір методу побудови шляху (крива, пряма, крива Безьє) або перехід в
нову точку:
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" > </canvas>
<script>
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width="300";
canvas.height="300";
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(150, 150);
ctx.lineTo(250, 150);
ctx.lineTo(200, 200);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fill();
</script>
</body>
</html>
Програма Смайлик
<!DOCTYPE html>
<html>
<body> false (за годинниковою стрілкою)
<canvas id="canvas" > </canvas> True (проти годиннкової стрілки)
<script>
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width="300";
canvas.height="300";
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Коло
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Посмішка
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Ліве око
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Праве око
ctx.stroke();
</script>
</body>
</html>
Програма «Смайлик-розфарбований»
ctx.font = "48px serif";
ctx.fillText("Hello!!!", 10, 180);
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Коло
ctx.fillStyle = 'rgb(255, 255, 0)';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // рот (за часовою стрілкою)
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Ліве око
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Праве око
ctx.fillStyle = 'rgb(0, 0, 255)';
ctx.fill();
ctx.stroke();
Творчий проект.