search
HomeWeb Front-endH5 Tutorial绘制SVG内容到Canvas的HTML5应用

SVG与Canvas是HTML5上绘制图形应用的两种完全不同模式的技术,两种绘制图形方式各有优缺点,但两者并非水火不容,尤其是SVG内容可直接绘制在Canvas上的功能,使得两者可以完美的融合在一起,让Canvas可享用到现有丰富的SVG素材,并不失SVG矢量无级缩放的特点。


基于HTML5的Drag and Drop生成图片Base64信息》这篇虽然展示的是拖拽普通栅格图片的效果,但你也可以直接拖拽SVG格式的图片进行显示,只不过普通图片的格式数据为data:image/png类型,而SVG格式的数据类型为data:image/svg+xml的类型,下图为该HT for Web拓扑图拖拽入SVG格式图片的运行效果:



1052.png

以下一段小例子,展示了加载一个SVG图片后,分为七个基本进行缩放绘制的效果,可看出Canvas绘制SVG可保持其矢量不失真的特性

function draw(){
    var img = new Image();
    img.src = 'chart.svg';
    document.body.appendChild(img);
    img.onload = function(){
        var canvas = document.getElementById('canvas');
        var g = canvas.getContext('2d'); 
        var width = img.clientWidth * 1.5;
        var height = img.clientHeight * 1.5;                
        var x = 2;
        var y = 2;
        for(var i=0; i<7; i++){
            g.drawImage(img, x, y, width, height);
            x += width + 2;
            width /= 2;
            height /= 2;
        }            
    };
}


1053.png

提到Canvas和SVG的融合,我们将采用HT for Web的矢量功能展示一个手机电池充电进度的实例,整个手机电池的静态部分我们通过加载一个简单的SVG素材实现,而充电动态变化的部分,我们采用一个渐进色的HT矩形元素来描述,该矩形的长度通过HT矢量数据动态绑定功能,根据充电进度的百分比换算成长度信息,最后通过定时器模拟数据变化达到动态充电的效果:

1054.png

ht.Default.setImage(&#39;battery&#39;, {  
    width: 64,  
    height: 64,  
    comps: [     
        {  
            type: &#39;rect&#39;,  
            rect: {  
                func: function(data){  
                    return [5, 25, 50*data.a(&#39;percent&#39;), 16]  
                }  
            },  
            background: &#39;red&#39;,  
            gradient: &#39;spread.vertical&#39;  
        },                          
        {  
            type: &#39;image&#39;,  
            name: &#39;battery.svg&#39;,  
            relative: true,  
            rect: [0, 0, 1, 1]  
        }  
    ]  
});                 
  
var node = new ht.Node();  
node.setPosition(80, 150);  
node.setImage(&#39;battery&#39;);  
node.s(&#39;image.stretch&#39;, &#39;uniform&#39;);  
node.a(&#39;percent&#39;, 0);  
dataModel.add(node);     
  
graphView.setEditable(true);  
  
setInterval(function(){  
    percent = node.a(&#39;percent&#39;) + 0.02;  
    if(percent > 1){  
        percent = 0;  
    }  
    node.a(&#39;percent&#39;, percent);  
}, 16);

SVG绘制到Canvas还有一种特殊的应用场景,就是将HTML元素通过SVG的foreignObject特性描述在SVG中,然后Canvas绘制SVG时,即可把foreignObject描述的HTML内容绘制到Canvas上,可参见https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas 的实例,其中采用了Blob的方式设置img的src作为URL是比较怪异的技术点,但从上文提到其实我们可以将整个SVG内容转换成data:image/svg+xml;的base64内容即可作为src的url传入,因此我对该例子做了改造,采用btoa(data)把svg内容转换成base64的方式设置img.src,这样方式更容易理解,例子代码和效果如下:http://v.youku.com/v_show/id_XODg0MTU4NjEy.html

1055.png

function draw(){  
    var canvas = document.getElementById(&#39;canvas&#39;);  
    var ctx = canvas.getContext(&#39;2d&#39;);  
    var data = 。。。;  
    var img = new Image();  
    img.onload = function () {  
        ctx.drawImage(img, 0, 0);  
    };              
    img.src = &#39;data:image/svg+xml;base64,&#39; + btoa(data);  
}

以上就是绘制SVG内容到Canvas的HTML5应用的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft