创建一个.net 7.0类库工程,引用下面的nuget包:

    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.5" />
<PackageReference Include="SkiaSharp.Views.Blazor" Version="2.88.3" /> 如果用到SkiaSharp就引入这个

然后把Project sdk改成这样:

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

然后c#代码可以这样写:

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.JSInterop; namespace WebAssemblyTest
{
public class Program
{
private static IJSRuntime js;
private static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
var host = builder.Build();
js = host.Services.GetRequiredService<IJSRuntime>();
RunInSeconds();
await host.RunAsync();
} static async void RunInSeconds()
{
while (true)
{
await Task.Delay(2000);
//调用javascript里面的test方法
await js.InvokeVoidAsync("test", new byte[] { 0x1, 0x2 });
}
} /// <summary>
/// 给js调用的函数
/// </summary>
/// <param name="i"></param>
/// <param name="j"></param>
/// <returns></returns>
[JSInvokable]
public static byte[] Add(int i, int j)
{
return new byte[] { (byte)i,(byte)j};
}
}
}

js代码这样写:

<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
</body>
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
<script>
function test(r) {
console.log(r);
alert(r);
}
window.onload = async function () {
await Blazor.start();
const r = await DotNet.invokeMethodAsync(
'WebAssemblyTest',//程序集的名字
'Add',//要调用的标注了[JSInvokable]方法的名字
666,//若干参数
333
);
console.log(r);
};
</script>
</html>

注意编译生成的_framework文件夹必须放在web服务器,并且设置mimeType以便前端可以顺利下载

var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".dll"] = "application/octet-stream";//配置添加新的映射关系
provider.Mappings[".gz"] = "application/octet-stream";
provider.Mappings[".dat"] = "application/octet-stream";
provider.Mappings[".blat"] = "application/octet-stream";
provider.Mappings[".pdb"] = "application/octet-stream";
provider.Mappings[".wasm"] = "application/octet-stream";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider,//应用新的映射关系
});

一个SkiaSharp显示图片到canvas的例子

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.JSInterop;
using SkiaSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices; namespace WebAssemblyTest
{
public class Program
{
private static IJSRuntime js;
private static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
var host = builder.Build();
js = host.Services.GetRequiredService<IJSRuntime>();
RunInSeconds();
await host.RunAsync();
} static async void RunInSeconds()
{
try
{ HttpClient client = new HttpClient();
using var ret = await client.GetStreamAsync("https://img0.baidu.com/it/u=189915953,3148055061&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800");
var bs = new byte[ret.Length];
ret.Read(bs , 0 , bs.Length);
ret.Dispose();
while (true)
{
using (var ms = new MemoryStream(bs))
{
ms.Position = 0;
using (var skiaBitmap = SKBitmap.Decode(ms))
{
// 获取图片的宽度和高度
var width = skiaBitmap.Width;
var height = skiaBitmap.Height;
using (var canvas = new SKCanvas(skiaBitmap))
{
// 添加文本
var paint = new SKPaint
{
IsAntialias = true,
Color = SKColors.Blue,
TextAlign = SKTextAlign.Center,
TextSize = 64
};
canvas.DrawText(DateTime.Now.ToString("测试 HH:mm:ss"), width / 2f, height / 2f, paint);
} // 创建一个用于存储像素数据的数组
var pixelData = new byte[width * height * 4]; // 将像素数据序列化到数组中
for (var y = 0; y < height; ++y)
{
for (var x = 0; x < width; ++x)
{
var index = (y * width + x) * 4;
var color = skiaBitmap.GetPixel(x, y);
pixelData[index] = color.Red;
pixelData[index + 1] = color.Green;
pixelData[index + 2] = color.Blue;
pixelData[index + 3] = color.Alpha;
}
} //调用javascript里面的test方法
await js.InvokeVoidAsync("test", pixelData, width, height);
}
}
await Task.Delay(25);
}
}
catch (Exception ex)
{
await js.InvokeVoidAsync("showErr", ex.ToString());
} } /// <summary>
/// 给js调用的函数
/// </summary>
/// <param name="i"></param>
/// <param name="j"></param>
/// <returns></returns>
[JSInvokable]
public static byte[] Add(int i, int j)
{
return new byte[] { (byte)i,(byte)j};
}
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<canvas id="myCanvas" style="width:800px;height:800px;"></canvas>
</body>
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
<script>
function test(data, width, height) {
const canvas = document.getElementById('myCanvas');
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.width = width;
context.height = height; const imageData = context.createImageData(width, height); for (let i = 0; i < data.length; i += 4) {
imageData.data[i] = data[i]; // 红色通道
imageData.data[i + 1] = data[i + 1]; // 绿色通道
imageData.data[i + 2] = data[i + 2]; // 蓝色通道
imageData.data[i + 3] = data[i + 3]; // alpha 通道
} context.putImageData(imageData, 0, 0);
}
function showErr(err) {
console.error(err);
}
window.onload = async function () {
await Blazor.start();
};
</script>
</html>

c# 编写 WebAssembly的更多相关文章

  1. 使用Go编写WebAssembly

    I. Install go 1. down https://golang.org/dl/ go1.12.3.windows-amd64.zip 2. set path (1) GOROOTvar na ...

  2. 不安分的 Go 语言开始入侵 Web 前端领域了!( WebAssembly )

    参考:https://blog.csdn.net/csdnnews/article/details/84038848 从 Go 语言诞生以来,它就开始不断侵蚀 Java .C.C++ 语言的领地.今年 ...

  3. webassembly

    为什么需要 WebAssembly 自从 JavaScript 诞生起到现在已经变成最流行的编程语言,这背后正是 Web 的发展所推动的.Web 应用变得更多更复杂,但这也渐渐暴露出了 JavaScr ...

  4. WebAssembly学习(三):AssemblyScript - TypeScript到WebAssembly的编译

    虽然说只要高级语言能转换成 LLVM IR,就能被编译成 WebAssembly 字节码,官方也推荐c/c++的方式,但是让一个前端工程师去熟练使用c/c++显然是有点困难,那么TypeScript ...

  5. 【webAssembly系列】webAssembly初探究竟

    一.前言 自从JavaScript诞生开始,到现在开始变成流行的编程语言,背后的是web发展所推动的.web应用的变得更多更复杂,但是渐渐暴露出JavaScript的问题: (1)语法太灵活导致开发大 ...

  6. 荷畔微风 - 在函数计算FunctionCompute中使用WebAssembly

    WebAssembly 是一种新的W3C规范,无需插件可以在所有现代浏览器中实现近乎原生代码的性能.同时由于 WebAssembly 运行在轻量级的沙箱虚拟机上,在安全.可移植性上比原生进程更加具备优 ...

  7. 简单的WebAssembly应用搭建

    1      WebAssembly简介 WebAssembly是一种新兴的Web技术,网上的资料并不是很多,简单的可以理解为让C/C++程序运行在浏览器上,官网上用四个词来描述该技术:高效.安全.开 ...

  8. 不用Blazor WebAssembly,开发在浏览器端编译和运行C#代码的网站

    本文中,我将会为大家分享一个如何用.NET技术开发"在浏览器端编译和运行C#代码的工具",核心的技术就是用C#编写不依赖于Blazor框架的WebAssembly以及Roslyn技 ...

  9. WHAT EXACTLY IS WASM ?!

    终于, 我入门了当初很仇视的技术.... 什么是WebAssembly? WebAssembly或WASM是一个编译器目标(由编译器生成的代码),具有二进制格式,允许我们在浏览器上执行C,C ++和R ...

  10. 别了,JavaScript;你好,Blazor

    Web开发与JavaScript开发向来是同义词.直到WebAssembly的横空出世,WebAssembly (Wasm)是一种在浏览器中可以执行的二进制指令. WebAssembly 的 官方工具 ...

随机推荐

  1. Java反序列化漏洞-CC1利用链分析

    @ 目录 一.前置知识 1. 反射 2. Commons Collections是什么 3. 环境准备 二.分析利用链 1. Transformer 2. InvokeTransformer 执行命令 ...

  2. 面试官:单例Bean一定不安全吗?实际工作中如何处理此问题?

    默认情况下,Spring Boot 中的 Bean 是非线程安全的.这是因为,默认情况下 Bean 的作用域是单例模式,那么此时,所有的请求都会共享同一个 Bean 实例,这意味着这个 Bean 实例 ...

  3. Programming Abstractions in C阅读笔记:p202-p234

    <Programming Abstractions in C>学习第65天,p202-p234总结. 一.技术总结 完成第五章学习,第五章介绍递归在实际问题中的进一步应用,例如汉诺塔问题, ...

  4. spring-cloud-alibaba项目打包

    在父依赖中加入 <build> <plugins> <plugin> <groupId>org.springframework.boot</gro ...

  5. 零代码搭建一个微信小程序

    本文分享自华为云社区<[新手指引]体验通过Astro Zero零代码快速搭建微信小程序>,作者:华为云Astro . 您将学会如何基于Astro零代码能力,DIY开发,完成问卷.投票.信息 ...

  6. 划重点!DWS开发的五大要点

    摘要:高效使用数据库是一个合格的开发工程师的必备技能,如何使用DWS进行高效开发,提升应用效率,技术干货来喽~~~ 高效使用数据库是一个合格的开发工程师的必备技能,如何使用DWS进行高效开发,提升应用 ...

  7. 理论+实践,揭秘昇腾CANN算子开发

    摘要: 本文介绍了CANN自定义算子开发的几种开发方式和算子的编译运行流程.然后以开发一个DSL Add算子为例,讲解算子开发的基本流程. 本文分享自华为云社区<昇腾CANN算子开发揭秘> ...

  8. 华为云应用服务网格最佳实践之从Spring Cloud 到 Istio

    摘要:在全球首届社区峰会IstioCon 2021中,华为云应用服务网格首席架构师张超盟发表了<Best practice:from Spring Cloud to Istio>主题演讲, ...

  9. 华为云发布ModelBox AI应用开发框架

    摘要:华为云ModelBox AI应用开发框架,打通端边云边界,助力开发者实现AI应用一次开发,全场景部署. 近日,以"因聚而生,为你所能"为主题的华为伙伴暨开发者大会 2022隆 ...

  10. 加快云原生技术转型, 智能调度登陆华为云DevOps: 增速,节源

    摘要:本文将探讨智能资源调度在华为云DevOps上的应用与实践. 本文分享自华为云社区<加快云原生技术转型, 智能调度登陆华为云DevOps: 增速,节源>,作者: DevAI. 1. 背 ...