1 / 9

CSc 337

Learn how to use the <canvas> HTML5 tag to create a flexible and powerful canvas that you can draw on. Explore drawing shapes, setting colors, animation, and more. Also, create a drawing program that allows users to draw with the mouse on a canvas.

Download Presentation

CSc 337

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSc 337 Lecture 18: Canvas

  2. Canvas • HTML 5 tag • creates a canvas that you can draw on • similar to DrawingPanel in CSC 110 • Flexible, powerful, useful but may not be fully implemented by all browsers <canvas width="100" height="100"></canvas>

  3. Canvas • To access your canvas: • var canvas = document.getElementById(id); • var ctx = canvas.getContext("2d"); • The context is like a pen. You can use it to draw on your canvas.

  4. Drawing Shapes • Setting colors: • ctx.fillStyle= colorString; • ctx.strokeStyle= colorString; • Rectangle • ctx.fillRect(x, y, width, height); • Circle • ctx.beginPath(); ctx.arc(x, y, radius, startAngle, endAngle);ctx.stroke(); • Line • ctx.moveTo(startX, startY);ctx.lineTo(endX, endY);ctx.stroke();

  5. Drawing Circles var c = document.getElementById("myCanvas");varctx = c.getContext("2d");ctx.beginPath();ctx.arc(100, 75, 50, 0, 2 * Math.PI);ctx.stroke();

  6. Animation • setInterval • This works fine but it is not as good • window.requestAnimationFrame(function) • better because it only draws when the browser wants to draw • function update() { • var canvas = document.getElementById("myCanvas"); • var ctx = canvas.getContext("2d"); • draw stuff • window.requestAnimationFrame(update); • }

  7. Activity • Write code to draw a circle on a canvas and make it move downward by one pixel every half second until it hits the bottom of the canvas. Once it hits the bottom make it move up by one pixel until it hits the top.

  8. Other Canvas Context Methods • Full list: https://www.w3schools.com/tags/ref_canvas.asp

  9. Activity: Drawing Program • Create a web page that allows the user to draw with the mouse on a canvas.

More Related