search
HomeWeb Front-endH5 TutorialIntroduction to the basic usage of HTML5 Canvas

本篇文章给大家带来的内容是关于HTML5 Canvas的基本用法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

canvas 是 HTML5 当中我最喜欢的所有新特性中我最喜欢的一个标签了。因为它太强大了,各种有意思的特效都可以实现。

1. canvas 的基本使用方法

- 它是一个行内块元素
- 默认大小是 300 x 150,不能在 css 里给他设置样式,只能在标签内写它的属性。如 width = 400,height = 300
- 获取画布
   var canvas = document。querySelector("canvas")
- 获取画笔(上下文)
   var ctx = canvas.getContext('2d')    

2. canvas 绘制基本的图形

填充矩形
ctx.fillRect(0,0,100,100)
fill:跟填充有关
Rect: 描绘一个矩形

填充图形设置样式
ctx.fillStyle = 'green'

描边矩形
ctx.strokeRect(100,100,100,100)

描边图形设置样式
ctx.strokeStyle = 'white'
ctx.lineWidth = 100

清除整个画布
ctx.clearRect(0,0,canvas.width,canvas.height)

画线段
ctx.moveTo(100,100)
ctx.lineTo(100,100)

描边
ctx.stroke()

填充
ctx.fill()-

起始点和结束点连接
ctx.closePath()
ctx.save()开头
   ......
ctx.restore()结尾

3. 画布时钟

使用画布我们可以画一个时钟,包括刻度和时针,每一秒走的刻度可以用 Data 对象通过定时器来时时更新。

var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");
    function move() {
        ctx.save()
            ctx.translate(300,300)
            //  初始化一些公共的样式
            ctx.lineCap = 'round'
            ctx.strokeStyle = 'black'
            ctx.lineWidth = 8
            ctx.scale(0.5,0.5)

            // 画外面的圆
            ctx.save();
                ctx.beginPath();
                ctx.strokeStyle = 'gold';
                ctx.arc(0,0,150,0,2*Math.PI);
                ctx.stroke();
            ctx.restore();

            // 画里面的刻度
            ctx.save()
                ctx.beginPath();
                for (var i=0; i <p>静止的图像如下图。</p><p style="text-align: center;"><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/207/367/164/1542961926883406.png?x-oss-process=image/resize,p_40" class="lazy" title="1542961926883406.png" alt="Introduction to the basic usage of HTML5 Canvas"></span></p><h4 id="刮刮卡效果">刮刮卡效果</h4><p>使用 canvas 的图形合成的属性可以实现图片合成的效果。具体应用于刮刮卡。<br>globalCompositeOperation属性设置或返回如何将一个源(新的)图像绘制到目标(已有)的图像上<br>源图像 = 您打算放置到画布上的绘图<br>目标图像 = 您已经放置在画布上的绘图</p><p   style="max-width:90%"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/360/936/462/1542961942862890.png?x-oss-process=image/resize,p_40" class="lazy" title="1542961942862890.png" alt="Introduction to the basic usage of HTML5 Canvas"></p><pre class="brush:php;toolbar:false">var  canvas = document.querySelector("canvas")
    var ctx = getCtx()
    log(ctx)
    ctx.fillStyle = 'yellow'
    ctx.fillRect(0,0,400,400)

    ctx.globalCompositeOperation = 'destination-out';

    // 鼠标按下
    canvas.onmousedown = function (event) {
        ctx.beginPath()
        ctx.arc(event.clientX - canvas.offsetLeft,event.clientY - canvas.offsetTop,
            20,0,2*Math.PI)
        ctx.fill()
        // 鼠标移动
        document.onmousemove = function (event) {
            ctx.beginPath()
            ctx.arc(event.clientX - canvas.offsetLeft,event.clientY - canvas.offsetTop,
            20,0,2*Math.PI)
            ctx.fill()
        }

        // 鼠标抬起
        document.onmouseup = function () {
            document.onmousemove = document.onmouseup = null
        }
        return false
    }

Introduction to the basic usage of HTML5 Canvas

The above is the detailed content of Introduction to the basic usage of HTML5 Canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools